#include "point.h"
#include "handle.h"
#include "upoint.h"
#include <iostream>

Handle::Handle():up(new UPoint){};
Handle::Handle(int x, int y):up(new UPoint(x, y)){};
Handle::Handle(const Point &p2) {
    up = new UPoint(p2);
}

Handle::Handle(const Handle &h){
    //指针的复制，只是将UPoint的u加1而已
    up = h.up;
    ++up->u;
};

Handle & Handle::operator=(const Handle &h)
{
    //等号左边的引用减一，等号右边的引用加一
    ++h.up->u;
    if (--up->u == 0)
    {
        delete up;
    }
    up = h.up;
    return *this;
}

Handle::~Handle() 
{
    if (--up->u == 0)
    {
        delete up;
    }
    using namespace std;
    cout << "Handle: " << this << " destoryed" << endl;
}

int Handle::x() const 
{
    return up->p.x();
}

int Handle::y() const 
{
    return up->p.y();
}

// 值语义，copy on write
Handle & Handle::x(int x0)
{
    if (up->u != 1)
    {
        --up->u;
        up = new UPoint(up->p);
    }
    
    up->p.x(x0);
    return *this;
}

// 值语义，copy on write
Handle & Handle::y(int y0)
{
    if (up->u != 1)
    {
        --up->u;
        up = new UPoint(up->p);
    }
    
    up->p.y(y0);
    return *this;
}
